const Cart = require("../model/cart.model")

const {Op} = require("sequelize")


class CartServer {
  // 查找商品id是否存在
  async getCardsId(id) {
    console.log(id)
    const res = await Cart.findOne({
      attributes: ['id', 'number'],
      where: {id: id}
    })
    console.log(res)
    return res
  }


  // 创建更新购物车
  async createOrUpdate(user_id, goods_id) {
    console.log(1212312)
    let res = await Cart.findOne({
      where: {
        [Op.and]: {
          user_id,
          goods_id
        }
      }
    })
    console.log(res)
    //已存在一条记录
    if (res) {
      await res.increment('number')
      return await res.reload()
    } else {
      return await Cart.create({
        user_id,
        goods_id
      })
    }
  }

  // 查找购物车列表
  async findCarts(pageNum, pageSize) {
    const offset = (pageNum - 1) * pageSize
    const {count, rows} = await Cart.findAndCountAll({
      attributes: ['id', 'number', 'selected'],
      offset: offset,
      limit: pageSize * 1,
      include: {
        model: Goods,
        as: "goods_info",
        attributes: ['id', 'goods_name', 'goods_price', 'goods_img']
      },
    })
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows
    }
  }

  async updateCarts(params) {
    const {id, number, selected} = params
    console.log(id)
    const res = await Cart.findByPk(id)
    console.log(res)
    if (!res) return ''

    number !== undefined ? (res.number = number) : ''
    selected !== undefined ? (res.selected = selected) : ''

    const result = res.save()

    return await res.save()
  }

  async deleteCarts(ids) {
    console.log(ids)
    const res = await Cart.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    })
    return res
  }

  async selectCartOrUnselect(user_id,selected){
    const res = await Cart.update({
      selected
    },{
      where:{
        user_id
      }
    })
    return res
  }
}

module.exports = new CartServer()
